package io.elegant.widgets

import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.google.protobuf.Any
import io.elegant.sessions.BaseSession
import io.elegant.toAny
import io.elegant.toStringValueOrNull
import kotlinx.coroutines.CoroutineScope
import kotlin.reflect.KClass

open class BaseTextWidget<T: View>(
    private val session: BaseSession,
    group: ViewGroup,
    cs: CoroutineScope
): BaseWidget<T>(session, group, cs) {
    override fun create(clazz: KClass<T>, sessionId: Long, futureId: Long, vararg argv: Any) {
        super.create(clazz, sessionId, futureId, *argv)
        (view as TextView?)?.text = argv[4].toStringValueOrNull()
    }
    override fun onReceive(name: String, sessionId: Long, futureId: Long, vararg argv: Any): Boolean {
        if (when (name) {
            "getText" -> getText(sessionId, futureId)
            "setText" -> setText(*argv)
            else -> null
        } == null)
            return super.onReceive(name, sessionId, futureId, *argv)
        return true
    }
    private fun getText(sessionId: Long, futureId: Long) {
        val text = (view as TextView?)?.text?.toString()
        onGetText(text.toAny(), sessionId, futureId)
    }
    private fun onGetText(text: Any, sessionId: Long, futureId: Long) = session.apply {
        sendAction("onGetText", sessionId, futureId, text)
    }
    private fun setText(vararg argv: Any) {
        (view as TextView?)?.text = argv[0].toStringValueOrNull()
    }
}